#pragma once
#include <iostream>
#include <string>
#include <fstream>
#include <unordered_map>
#include "Log.hpp"

static const std::string flag = ": ";

class Dictionary
{
    void LoadConf()
    {
        std::ifstream in(_path); // 打开文件
        if (!in.is_open())
        {
            return;
        }
        std::string line;
        while (std::getline(in, line))
        {
            LOG(LogLevel::DEBUG) << "load dict message:  " << line;
            // apple: 苹果
            // 字符切割
            auto pos = line.find(flag);
            if (pos == std::string::npos)//没找到分隔符
            {
                LOG(LogLevel::WARING) << "format error" << line;
                continue;
            }

            std::string word = line.substr(0, pos);             // 截取分隔符之前的字符
            std::string value = line.substr(pos + flag.size()); // 截取分隔符之后的字符
            if (word.empty() || value.empty())
            {
                LOG(LogLevel::WARING) << "format error, word or value is empty" << line;
                continue;
            }
            _dict.insert(std::make_pair(word, value)); // 插入字典
        }
        in.close(); // 关闭文件
    }

public:
    Dictionary(std::string path) : _path(path)
    {
        LoadConf();
    }
    std::string Translate(const std::string &word, const std::string &whoip, uint16_t whoport)
    {
        (void)whoip;
        (void)whoport;
        auto iter = _dict.find(word); // 查询单词
        if (iter == _dict.end())
        {
            return "UNKNOWN"; // 没找到的情况
        }
        return iter->second; // 返回中文翻译
    }
    ~Dictionary() {}

private:
    std::unordered_map<std::string, std::string> _dict;
    std::string _path;
};